<template>
  <div class="exchange-code-management">
    <h2>{{ t('admin.menu.exchangeCodes') }}</h2>
    <p>{{ t('admin.exchangeCodes.description') }}</p>
    
    <!-- Exchange code management controls -->
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <span>{{ t('admin.exchangeCodes.exchangeCodeList') }}</span>
          <el-button type="primary" @click="openExchangeCodeForm">
            {{ t('admin.exchangeCodes.addExchangeCode') }}
          </el-button>
          <el-button type="success" @click="generateBatchCodes">
            {{ t('admin.exchangeCodes.generateBatchCodes') }}
          </el-button>
        </div>
      </template>
      
      <!-- Search and filter -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="filters.code" 
              :placeholder="t('admin.exchangeCodes.code')"
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.status" 
              :placeholder="t('admin.exchangeCodes.status')"
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="status in statuses" 
                :key="status.value" 
                :label="t(`admin.exchangeCodes.status.${status.value.toLowerCase()}`)"
                :value="status.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.expirationDate"
              type="date"
              :placeholder="t('admin.exchangeCodes.expirationDate')"
              style="width: 100%"
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchExchangeCodes">
              {{ t('common.search') }}
            </el-button>
            <el-button @click="resetFilters">
              {{ t('common.reset') }}
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- Exchange code table -->
      <el-table :data="exchangeCodes" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" :label="t('admin.exchangeCodes.id')" width="80"></el-table-column>
        <el-table-column prop="code" :label="t('admin.exchangeCodes.code')"></el-table-column>
        <el-table-column prop="merchantId" :label="t('admin.exchangeCodes.merchantId')"></el-table-column>
        <el-table-column :label="t('admin.exchangeCodes.status')">
          <template #default="scope">
            <el-tag 
              :type="getExchangeCodeStatusType(scope.row.status)" 
              disable-transitions
            >
              {{ t(`admin.exchangeCodes.status.${scope.row.status.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" :label="t('admin.exchangeCodes.expirationDate')">
          <template #default="scope">
            {{ formatDate(scope.row.expirationDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" :label="t('admin.exchangeCodes.createdAt')">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="usedAt" :label="t('admin.exchangeCodes.usedAt')">
          <template #default="scope">
            {{ scope.row.usedAt ? formatDate(scope.row.usedAt) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="usedBy" :label="t('admin.exchangeCodes.usedBy')"></el-table-column>
        <el-table-column :label="t('common.actions')" width="250">
          <template #default="scope">
            <el-button size="small" @click="viewExchangeCode(scope.row)">
              {{ t('common.view') }}
            </el-button>
            <el-button size="small" @click="editExchangeCode(scope.row)">
              {{ t('common.edit') }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteExchangeCode(scope.row)">
              {{ t('common.delete') }}
            </el-button>
            <el-button size="small" type="warning" @click="cancelExchangeCode(scope.row)" v-if="scope.row.status === 'UNUSED'">
              {{ t('admin.exchangeCodes.cancel') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- Exchange code form dialog -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetExchangeCodeForm"
    >
      <el-form 
        :model="exchangeCodeForm" 
        :rules="exchangeCodeRules" 
        ref="exchangeCodeFormRef" 
        label-width="150px"
      >
        <el-form-item :label="t('admin.exchangeCodes.code')" prop="code">
          <el-input v-model="exchangeCodeForm.code"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.merchantId')" prop="merchantId">
          <el-input-number 
            v-model="exchangeCodeForm.merchantId" 
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.status')" prop="status">
          <el-select v-model="exchangeCodeForm.status" style="width: 100%">
            <el-option 
              v-for="status in statuses" 
              :key="status.value" 
              :label="t(`admin.exchangeCodes.status.${status.value.toLowerCase()}`)"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.expirationDate')" prop="expirationDate">
          <el-date-picker
            v-model="exchangeCodeForm.expirationDate"
            type="date"
            :placeholder="t('admin.exchangeCodes.enterExpirationDate')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.usedBy')" prop="usedBy">
          <el-input v-model="exchangeCodeForm.usedBy"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="saveExchangeCode">{{ t('common.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- Batch generation dialog -->
    <el-dialog 
      v-model="batchDialogVisible" 
      :title="t('admin.exchangeCodes.generateBatchCodes')" 
      width="500px"
    >
      <el-form 
        :model="batchForm" 
        :rules="batchRules" 
        ref="batchFormRef" 
        label-width="150px"
      >
        <el-form-item :label="t('admin.exchangeCodes.batchCount')" prop="count">
          <el-input-number 
            v-model="batchForm.count" 
            :min="1" 
            :max="1000"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.merchantId')" prop="merchantId">
          <el-input-number 
            v-model="batchForm.merchantId" 
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.exchangeCodes.expirationDate')" prop="expirationDate">
          <el-date-picker
            v-model="batchForm.expirationDate"
            type="date"
            :placeholder="t('admin.exchangeCodes.enterExpirationDate')"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="generateBatchExchangeCodes">{{ t('common.generate') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'

export default {
  name: 'ExchangeCodeManagement',
  setup() {
    const { t } = useI18n()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const batchDialogVisible = ref(false)
    const dialogTitle = ref('')
    const exchangeCodeFormRef = ref(null)
    const batchFormRef = ref(null)
    
    const exchangeCodes = ref([])
    const selectedExchangeCodes = ref([])
    
    const filters = reactive({
      code: '',
      status: '',
      expirationDate: null
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const exchangeCodeForm = reactive({
      id: null,
      code: '',
      merchantId: 1,
      status: 'UNUSED',
      expirationDate: null,
      createdAt: null,
      usedAt: null,
      usedBy: ''
    })
    
    const batchForm = reactive({
      count: 10,
      merchantId: 1,
      expirationDate: null
    })
    
    const statuses = ref([
      { value: 'UNUSED', label: t('admin.exchangeCodes.status.unused') },
      { value: 'USED', label: t('admin.exchangeCodes.status.used') },
      { value: 'EXPIRED', label: t('admin.exchangeCodes.status.expired') },
      { value: 'CANCELLED', label: t('admin.exchangeCodes.status.cancelled') }
    ])
    
    const exchangeCodeRules = {
      code: [
        { required: true, message: t('admin.exchangeCodes.enterCode'), trigger: 'blur' }
      ],
      merchantId: [
        { required: true, message: t('admin.exchangeCodes.enterMerchantId'), trigger: 'blur' }
      ],
      status: [
        { required: true, message: t('admin.exchangeCodes.selectStatus'), trigger: 'blur' }
      ],
      expirationDate: [
        { required: true, message: t('admin.exchangeCodes.enterExpirationDate'), trigger: 'blur' }
      ]
    }
    
    const batchRules = {
      count: [
        { required: true, message: t('admin.exchangeCodes.enterBatchCount'), trigger: 'blur' }
      ],
      merchantId: [
        { required: true, message: t('admin.exchangeCodes.enterMerchantId'), trigger: 'blur' }
      ],
      expirationDate: [
        { required: true, message: t('admin.exchangeCodes.enterExpirationDate'), trigger: 'blur' }
      ]
    }
    
    const getExchangeCodeStatusType = (status) => {
      const statusTypes = {
        UNUSED: 'info',
        USED: 'success',
        EXPIRED: 'warning',
        CANCELLED: 'danger'
      }
      return statusTypes[status] || 'info'
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }
    
    const loadExchangeCodes = async () => {
      try {
        loading.value = true
        // In a real application, you would make an API call to fetch exchange codes
        // For now, using mock data
        exchangeCodes.value = [
          {
            id: 1,
            code: 'EXCH123456',
            merchantId: 1,
            status: 'UNUSED',
            expirationDate: '2025-12-31',
            createdAt: '2025-10-28',
            usedAt: null,
            usedBy: ''
          },
          {
            id: 2,
            code: 'EXCH789012',
            merchantId: 1,
            status: 'USED',
            expirationDate: '2025-11-30',
            createdAt: '2025-10-27',
            usedAt: '2025-10-28',
            usedBy: 'customer1'
          },
          {
            id: 3,
            code: 'EXCH345678',
            merchantId: 2,
            status: 'EXPIRED',
            expirationDate: '2025-09-30',
            createdAt: '2025-09-01',
            usedAt: null,
            usedBy: ''
          }
        ]
        pagination.total = exchangeCodes.value.length
      } catch (error) {
        console.error('Error loading exchange codes:', error)
        ElMessage.error(t('admin.exchangeCodes.errorLoadingExchangeCodes'))
      } finally {
        loading.value = false
      }
    }
    
    const searchExchangeCodes = () => {
      loadExchangeCodes()
    }
    
    const resetFilters = () => {
      filters.code = ''
      filters.status = ''
      filters.expirationDate = null
      loadExchangeCodes()
    }
    
    const openExchangeCodeForm = () => {
      dialogTitle.value = t('admin.exchangeCodes.addExchangeCode')
      dialogVisible.value = true
    }
    
    const editExchangeCode = (exchangeCode) => {
      dialogTitle.value = t('admin.exchangeCodes.editExchangeCode')
      Object.assign(exchangeCodeForm, exchangeCode)
      dialogVisible.value = true
    }
    
    const viewExchangeCode = (exchangeCode) => {
      dialogTitle.value = t('admin.exchangeCodes.viewExchangeCode')
      Object.assign(exchangeCodeForm, exchangeCode)
      dialogVisible.value = true
    }
    
    const deleteExchangeCode = (exchangeCode) => {
      // In a real application, you would make an API call to delete the exchange code
      console.log('Delete exchange code:', exchangeCode)
      ElMessage.success(t('admin.exchangeCodes.exchangeCodeDeleted'))
      loadExchangeCodes()
    }
    
    const cancelExchangeCode = (exchangeCode) => {
      // In a real application, you would make an API call to cancel the exchange code
      exchangeCode.status = 'CANCELLED'
      console.log('Cancel exchange code:', exchangeCode)
      ElMessage.success(t('admin.exchangeCodes.exchangeCodeCancelled'))
      loadExchangeCodes()
    }
    
    const saveExchangeCode = async () => {
      await exchangeCodeFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // In a real application, you would make an API call to save the exchange code
            console.log('Saving exchange code:', exchangeCodeForm)
            dialogVisible.value = false
            ElMessage.success(t('admin.exchangeCodes.exchangeCodeSaved'))
            loadExchangeCodes()
          } catch (error) {
            console.error('Error saving exchange code:', error)
            ElMessage.error(t('admin.exchangeCodes.errorSavingExchangeCode'))
          }
        }
      })
    }
    
    const resetExchangeCodeForm = () => {
      Object.keys(exchangeCodeForm).forEach(key => {
        if (key === 'merchantId') {
          exchangeCodeForm[key] = 1
        } else if (key === 'status') {
          exchangeCodeForm[key] = 'UNUSED'
        } else {
          exchangeCodeForm[key] = null
        }
      })
    }
    
    const generateBatchCodes = () => {
      batchDialogVisible.value = true
    }
    
    const generateBatchExchangeCodes = async () => {
      await batchFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // In a real application, you would make an API call to generate batch codes
            console.log('Generating batch exchange codes:', batchForm)
            batchDialogVisible.value = false
            ElMessage.success(t('admin.exchangeCodes.batchCodesGenerated'))
            loadExchangeCodes()
          } catch (error) {
            console.error('Error generating batch exchange codes:', error)
            ElMessage.error(t('admin.exchangeCodes.errorGeneratingBatchCodes'))
          }
        }
      })
    }
    
    const handleSelectionChange = (selection) => {
      selectedExchangeCodes.value = selection
    }
    
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadExchangeCodes()
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadExchangeCodes()
    }
    
    onMounted(() => {
      loadExchangeCodes()
    })
    
    return {
      t,
      loading,
      dialogVisible,
      batchDialogVisible,
      dialogTitle,
      exchangeCodeFormRef,
      batchFormRef,
      exchangeCodes,
      selectedExchangeCodes,
      filters,
      pagination,
      exchangeCodeForm,
      batchForm,
      statuses,
      exchangeCodeRules,
      batchRules,
      getExchangeCodeStatusType,
      formatDate,
      loadExchangeCodes,
      searchExchangeCodes,
      resetFilters,
      openExchangeCodeForm,
      editExchangeCode,
      viewExchangeCode,
      deleteExchangeCode,
      cancelExchangeCode,
      saveExchangeCode,
      resetExchangeCodeForm,
      generateBatchCodes,
      generateBatchExchangeCodes,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.exchange-code-management {
  padding: 20px;
}

.management-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>